package client

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"me/123/common/proto/order"
)

type OrderHandler func(ctx context.Context, in order.OrderClient) (interface{}, error)

func OrderClient(ctx context.Context, handler OrderHandler) (interface{}, error) {
	conn, err := grpc.Dial("127.0.0.1:8081", grpc.WithInsecure())
	if err != nil {
		fmt.Printf("连接异常： %s\n", err)
		return nil, err
	}
	defer conn.Close()
	client := order.NewOrderClient(conn)
	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}
	return res, err
}

func OrderCreate(ctx context.Context, req *order.OrderCreateRequest) (*order.OrderCreateResponse, error) {
	client, err := OrderClient(ctx, func(ctx context.Context, in order.OrderClient) (interface{}, error) {
		login, err := in.OrderCreate(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, err
	})
	if err != nil {
		return nil, err
	}
	return client.(*order.OrderCreateResponse), err
}

func UpdateOrderStatus(ctx context.Context, req *order.UpdateOrderStatusRequest) (*order.UpdateOrderStatusResponse, error) {
	client, err := OrderClient(ctx, func(ctx context.Context, in order.OrderClient) (interface{}, error) {
		login, err := in.UpdateOrderStatus(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, err
	})
	if err != nil {
		return nil, err
	}
	return client.(*order.UpdateOrderStatusResponse), err
}
